package ro.sergiu.finder.filters;

import java.beans.Beans;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Toporjinschi
 * @param <M> the type of verification item (ex. String if is a db connection, class if is a bean
 * search)
 * @param <V> type of value could (ex. String if the control is a text field and the referenced
 * column from db is also of type string)
 */
public class ComboFilter<M, V> extends FilterPanelUI<M, V> {

    private Map<String, V> itemMap;

    public ComboFilter(String title, M mappingItem, Operator operator) {
        super(title, mappingItem, operator);
        initComponents();
        this.itemMap = new HashMap<String, V>();
        this.combo.removeAllItems();
        this.combo.addItem("Toate");
    }

    /**
     * Adds a new element to combo;
     *
     * @param key represents the value which will be used in SQL Query;
     * @param text represents the value which will be displayed for user, in interface;
     */
    public void addItem(String text, V key) {
        this.itemMap.put(text, key);
        this.combo.addItem(text);
    }

    /**
     * Allows to give a new data set containing the text and the values, to populate the combo-box;
     *
     * @param values the map containing the values and the test.
     *
     */
    public void setItems(Map<String, V> values) {
        this.itemMap = values;
    }

    public ComboFilter() {
        if (!Beans.isDesignTime()) {
            throw new IllegalArgumentException("Illegal call of constructor " + this.getClass().getName() + ". Should be used only in design time.");
        }
        this.itemMap = new HashMap<String, V>();
        initComponents();
    }

    @Override
    public V getValue() {
        if (this.combo.getSelectedIndex() == 0) {
            return null;
        }
        return this.itemMap.get((String) this.combo.getSelectedItem());
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        combo = new javax.swing.JComboBox();

        setLayout(new java.awt.BorderLayout());

        combo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        add(combo, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox combo;
    // End of variables declaration//GEN-END:variables

}
